class AudioManager {
    static audioMap = new Map();
    static bgmPlaying = false;

    static async loadAll() {
        const audioFiles = {
            bgm: './Overworld.mp3',
            jump_small: './JumpSmall.mp3',
            jump_super: './JumpSuper.mp3'
        };

        for (const [name, url] of Object.entries(audioFiles)) {
            const audio = new Audio(url);
            audio.preload = 'auto';
            this.audioMap.set(name, audio);
        }
    }

    static async load(name, url) {
        const audio = new Audio(url);
        audio.preload = 'auto';
        this.audioMap.set(name, audio);
        return audio;
    }

    static get(name) {
        return this.audioMap.get(name);
    }

    static remove(name) {
        const audio = this.audioMap.get(name);
        if (audio) {
            audio.pause();
            audio.src = '';
        }
        this.audioMap.delete(name);
    }

    static async play(name, options = {}) {
        const audio = this.audioMap.get(name);
        if (!audio) return false;

        const { loop = false, volume = 1 } = options;
        
        audio.loop = loop;
        audio.volume = volume;
        
        try {
            await audio.play();
            return true;
        } catch (e) {
            console.error(`Failed to play audio ${name}:`, e);
            return false;
        }
    }

    static stop(name) {
        const audio = this.audioMap.get(name);
        if (audio) {
            audio.pause();
            audio.currentTime = 0;
        }
    }

    static pause(name) {
        const audio = this.audioMap.get(name);
        if (audio) {
            audio.pause();
        }
    }

    static async playBGM() {
        if (!this.bgmPlaying) {
            this.bgmPlaying = true;
            await this.play('bgm', { loop: true, volume: 0.1 });
        }
    }

    static stopBGM() {
        this.bgmPlaying = false;
        this.stop('bgm');
    }

    static async playJumpSound() {
        await this.play('jump_small', { volume: 0.5 });
    }

    static setVolume(name, volume) {
        const audio = this.audioMap.get(name);
        if (audio) {
            audio.volume = Math.max(0, Math.min(1, volume));
        }
    }

    static pauseAll() {
        this.audioMap.forEach(audio => audio.pause());
    }

    static resumeAll() {
        this.audioMap.forEach(audio => {
            if (audio.currentTime > 0 && audio.paused) {
                audio.play().catch(console.error);
            }
        });
    }
    
    static destroy() {
        this.audioMap.forEach(audio => {
            audio.pause();
            audio.src = '';
        });
        this.audioMap.clear();
        this.bgmPlaying = false;
    }
}

export default AudioManager;